//
//  VVSportCameraConteoller.m
//  DingDingSport
//
//  Created by 王惠平 on 2017/4/28.
//  Copyright © 2017年 will wang. All rights reserved.
//

#import "VVSportCameraConteoller.h"
#import <AVFoundation/AVFoundation.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface VVSportCameraConteoller ()
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *cameraConstraints;

//输入设备
@property (nonatomic, strong) AVCaptureDeviceInput *input;
//输出设备
@property (nonatomic, strong) AVCaptureStillImageOutput *output;

//会话
@property (nonatomic, strong) AVCaptureSession * session;

//预览视图
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

//相机预览视图
@property (weak, nonatomic) IBOutlet UIView *cameraView;

//对调摄像头按钮
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;

//运动图片水印
@property (weak, nonatomic) IBOutlet UIImageView *sportImgV;

//运动距离水印
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;

//图片保存动画label
@property (weak, nonatomic) IBOutlet UILabel *imgSaveLabel;
@property (weak, nonatomic) IBOutlet UIButton *cameraBtn;

//保存的图片
@property (nonatomic, strong) UIImage *savedImg;


@end

@implementation VVSportCameraConteoller

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupCamera];
    
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f km",self.track.totalDistance];
    
}

//照相机
- (void)setupCamera{
    
    //输入设备 摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    //输出设备
    self.output = [[AVCaptureStillImageOutput alloc]init];
    
    //会话
    self.session = [[AVCaptureSession alloc]init];
    
    //添加输入/输出设备
    if ([self.session canAddInput:self.input]) {
        
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.output]) {
        
        [self.session addOutput:self.output];
    }
    
    //预览视图layer
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    
    [self.cameraView.layer insertSublayer:self.previewLayer atIndex:0];
    
    //设置预览视图样式
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    //开始会话
    [self.session startRunning];
    
}

//拍照
- (void) takePicture {
    
    //执行拍照
    [self.output captureStillImageAsynchronouslyFromConnection:self.output.connections.firstObject completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        //获取二进制文件
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        UIImage *img = [UIImage imageWithData:data];
        
        //对图片caiqie
        //获取要裁切的大小
        CGFloat offset = ([UIScreen mainScreen].bounds.size.height - self.cameraView.frame.size.height) * 0.5;
        
        CGRect tarRect = CGRectInset(self.cameraView.frame, 0, -offset);
        
        //创建上下文
        //UIGraphicsBeginImageContext(self.cameraView.frame.size);
        //创建图片上下文 上下文的尺寸就是最终图片的尺寸  如果希望使用当前设备的分辨率生成图片,需要设置Option中scale属性为0,如果没有设置的话,会使用默认的分辨率(480*320)生成图片
        UIGraphicsBeginImageContextWithOptions(self.cameraView.frame.size, YES, 0);
        
        //将图片画到上下文
        [img drawInRect:tarRect];
        
        //添加文字水印
        [self.distanceLabel.attributedText drawInRect:self.distanceLabel.frame];
        
        //添加图片上下文
        [self.sportImgV.image drawInRect:self.sportImgV.frame];
        
        //从上下文获取图片
        UIImage *editedImg = UIGraphicsGetImageFromCurrentImageContext();
        
        //关闭上下文
        UIGraphicsEndImageContext();
        
        //保存到相册
        UIImageWriteToSavedPhotosAlbum(editedImg, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        
        //记录图片
        self.savedImg = editedImg;


    }];
}

//保存图片后的回调
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    
    //执行动画
    [self rotateAnim];
    
    //停止采集
    [self.session stopRunning];
    
    //打开快门
    [self cameraWithClose:NO];
    
    //设置延迟 等快门动画执行到一半时显示文本
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.imgSaveLabel.alpha = 1.0;
        
        self.imgSaveLabel.text = (error == nil) ? @"图片保存成功" : @"图片保存失败";
        
        //设置动画
        [UIView animateWithDuration:1 animations:^{
            
            self.imgSaveLabel.alpha = 0;
        }];
    });
    
}


- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    self.previewLayer.frame = self.cameraView.bounds;
}

//执行快门
- (void)cameraWithClose:(BOOL)close {
    
    //iOS推荐使用禁用/启用约束的方式来调整视图的约束,而不推荐使用更新/删除约束的方式来调整视图(这种方式性能较差)
    if (close) {
        
        //禁用约束
        [NSLayoutConstraint deactivateConstraints:self.cameraConstraints];
    } else {
        
        //启用动画
        [NSLayoutConstraint activateConstraints:self.cameraConstraints];
    }
    
    //设置动画
    [UIView animateWithDuration:1.25 animations:^{
        
        [self.view layoutIfNeeded];
    }];
}

//响应事件
//切换摄像头分享
- (IBAction)clickChangeBtn:(UIButton *)sender {
    
    //判断会话是否正在执行 区分摄像头对调/分享
    if (!self.session.isRunning) {
        
        //分享图片
        [self shareImg];
        return;
    }

    
    //停止采集
    [self.session stopRunning];
    
    //切换状态
    sender.selected = !sender.selected;
    
    //获取设备
    AVCaptureDevice *device = [self getChangeDevice];
    
    //会话添加新输入设备前,需要移除已经添加的设备
    [self.session removeInput:self.input];
    
    //设置输入设备
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    //重新关联会话
    if ([self.session canAddInput:self.input]) {
        
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.output]) {
        
        [self.session addOutput:self.output];
    }
    
    //重新采集信息
    [self.session startRunning];
}

//分享图片
- (void)shareImg{
    
    //1、创建分享参数
    NSArray* imageArray = @[self.savedImg];
    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //有的平台要客户端分享需要加此方法，例如微博
        [shareParams SSDKEnableUseClientShare];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
        [ShareSDK showShareActionSheet:nil items:nil shareParams:shareParams onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
            
            switch (state) {
                case SSDKResponseStateSuccess:
                {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                        message:nil
                                                                       delegate:nil
                                                              cancelButtonTitle:@"确定"
                                                              otherButtonTitles:nil];
                    [alertView show];
                    break;
                }
                case SSDKResponseStateFail:
                {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                    message:[NSString stringWithFormat:@"%@",error]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil, nil];
                    [alert show];
                    break;
                }
                default:
                    break;
            }
        }
         ];}
}


//获取设备
- (AVCaptureDevice *)getChangeDevice {
    
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    //选中按钮使用前置,没有选中使用后置
    AVCaptureDevicePosition position = self.changeBtn.selected ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
    
    for (AVCaptureDevice *device in devices) {
        
        if (device.position == position) {
            
            return device;
        }
    }
  
    return devices.firstObject;
}

//点击拍照
- (IBAction)clickCameraBtn:(id)sender {
    
    if (self.session.isRunning == NO) {
        
        //执行翻转动画
        [self rotateAnim];
        
        //开始采集
        [self.session startRunning];
        
        return;
    }
    
    //关闭快门
    [self cameraWithClose:YES];
    
    //执行拍照
    [self takePicture];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        //打开快门
//        [self cameraWithClose:NO];
//    });

}

//设置翻转动画
- (void)rotateAnim {
    
    //拍摄状态下点击按钮: 文字从无到有 按钮进行从右向左翻转  切换图片(对调摄像头->分享) 停止采集信息
    //照片状态下点击按钮: 文字从有到无 按钮进行从左向右翻转  切换图片 分享->对调摄像头 开始采集信息

    //设置文字
    NSString *title = self.session.isRunning ? @"✓" : nil;
    
    [self.cameraBtn setTitle:title forState:UIControlStateNormal];
    
    //设置翻转动画
    UIViewAnimationOptions option = self.session.isRunning ? UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft;
    
    [UIView transitionWithView:self.cameraBtn duration:0.5 options:option animations:nil completion:nil];
    
    [UIView transitionWithView:self.changeBtn duration:0.5 options:option animations:nil completion:nil];
    
    //切换图片
    NSString *imgName = self.session.isRunning ? @"ic_waterprint_share" : @"ic_waterprint_revolve";
    
    [self.changeBtn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];

}

//可以设置单个控制器不显示状态栏
- (BOOL)prefersStatusBarHidden {
    
    return YES;
}


- (IBAction)clickCloseBtn:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
